<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\common\service\driver\OrderService;
use think\addons\Controller;
use Exception;

/**
 * 微信支付宝支付
 * @ApiWeigh (99)
 */
class Pay extends Controller
{

    /**
     * 提交订单
     *
     * @param array $params
     * @param string $type
     * @ApiInternal
     **/
    public static function experience($params, $type)
    {
        $notifyurl = request()->root(true) . '/api/pay/notifyx/paytype/' . $params['type'] . '/type/' . $type;
        $returnurl = request()->root(true) . '/api/pay/returnx/paytype/' . $params['type'] . '/type/' . $type . '/out_trade_no/' . $params['orderid'];

        $params['notifyurl'] = $notifyurl;
        $params['returnurl'] = $returnurl;
        $response = Service::submitOrder($params);
        return $response;
    }

    /**
     * 支付成功
     *
     * @ApiInternal
     */
    public function notifyx()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $trade_no = $paytype == 'alipay' ? $data['trade_no'] : $data['transaction_id'];

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑
            $type = $this->request->param('type');
            switch ($type) {
                case 'order':
                    $result = OrderService::order_settle($payamount, $out_trade_no, $trade_no, $paytype);
                    break;
            }
            if ($result['code'] == 0) {
                // 告诉支付宝微信，我已经处理完了，订单没找到，别再通知我了
                user_log($paytype, $out_trade_no . ' ' . $result['msg']);
            }
        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }
    public function notifyx_transfer()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        user_log($paytype.'_transfer', $pay);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();
        user_log($paytype.'_transfer', $data);
        try {

        } catch (Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }

    /**
     * 支付返回
     *
     * @ApiInternal
     */
    public function returnx()
    {
        $paytype = $this->request->param('paytype');
        $out_trade_no = $this->request->param('out_trade_no');
        $pay = Service::checkReturn($paytype);
        if (!$pay) {
            $this->error('签名错误', '');
        }

        //你可以在这里定义你的提示信息,但切记不可在此编写逻辑
        $this->success("请返回网站查看支付结果", addon_url("epay/index/index"));
//        $this->redirect($result);
    }

    /**
     * 查询订单
     *
     * @ApiMethod (POST)
     * @ApiParams (name="order_id", type="string", required=true, description="订单号")
     * @ApiReturn ({"code":1,"msg":"SUCCESS","time":"1720497307","data":{"status":"订单状态","end_code":"交车码"}})
     **/
    public function order_query()
    {
        // TODO 20240711
        $paytype = $this->request->param('paytype', 'wechat');
        $out_trade_no = $this->request->param('order_id');
        if (!$out_trade_no) {
            exit(json_encode(V(0, '订单参数错误'), JSON_UNESCAPED_UNICODE));
        }
//        $pay = Service::orderQuery($paytype, $out_trade_no);
//        if ($pay['trade_state'] == 'SUCCESS') {
        $result = OrderService::order_query($out_trade_no);
        exit(json_encode(V(1, '支付成功', $result), JSON_UNESCAPED_UNICODE));
//        }
//        exit(json_encode(V(0,$pay['trade_state_desc']),JSON_UNESCAPED_UNICODE));

        // 返回示例
        // {
        //        "code": "10000",
        //        "msg": "Success",
        //        "buyer_logon_id": "151******82",
        //        "buyer_pay_amount": "0.01",
        //        "buyer_user_id": "2088232441635291",
        //        "fund_bill_list": [
        //            {
        //                "amount": "0.01",
        //                "fund_channel": "PCREDIT"
        //            }
        //        ],
        //        "invoice_amount": "0.01",
        //        "out_trade_no": "M202111021635838811584945",
        //        "point_amount": "0.00",
        //        "receipt_amount": "0.01",
        //        "send_pay_date": "2021-11-02 15:40:23",
        //        "total_amount": "0.01",
        //        "trade_no": "2021110222001435295732335876",
        //        "trade_status": "TRADE_SUCCESS"
        //    }
        //{
        //        "return_code": "SUCCESS",
        //        "return_msg": "OK",
        //        "result_code": "SUCCESS",
        //        "mch_id": "1490336182",
        //        "appid": "wx04ac30fdcb1a8cc4",
        //        "openid": "o-nEUvw6d35BiEGfb_p-4nFb0pzk",
        //        "is_subscribe": "N",
        //        "trade_type": "MWEB",
        //        "trade_state": "SUCCESS",
        //        "bank_type": "OTHERS",
        //        "total_fee": "1",
        //        "fee_type": "CNY",
        //        "cash_fee": "1",
        //        "cash_fee_type": "CNY",
        //        "transaction_id": "4200001305202111030926926690",
        //        "out_trade_no": "M202111031635919528418193",
        //        "attach": [],
        //        "time_end": "20211103140602",
        //        "trade_state_desc": "支付成功",
        //        "nonce_str": "cnUi4xviWAHQNQKy",
        //        "sign": "CBE6B8EC917F0862A3E0C6C0874678F9"
        //    }
    }

}
